package com.yxhl.zoume.common.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.support.annotation.ColorRes;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.core.busticket.event.SelectLetterEvent;
import com.yxhl.zoume.data.rxbus.RxBus;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * Created by sugarya on 2016/07/25.
 * 字母表自定义控件
 */
public class AlphabetLinearLayout extends LinearLayout implements View.OnTouchListener {

    private static final String TAG = "AlphabetLinearLayout";

    private static final String[] mLetters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    /**
     * 默认相邻两个字母在字母表里间距
     */
    private static final int DEFAULT_LETTER_PADDING_RIGHT = 8;

    /**
     * 默认字母在字母表里的水平间距
     */
    private static final int DEFAULT_LETTER_PADDING_LEFT = 8;

    /**
     * 屏幕适配因子
     */
    private static final float SCREEN_COMPAT_FACTOR = 1.25f;

    /**
     * 显示在屏幕中央的字母大小/dp
     */
    private static final float DEFAULT_SCREEN_LETTER_SIZE = 36;

    /**
     * 字母表里字母大小/dp
     */
    private static final float DEFAULT_ALPHABET_LETTER_SIZE = 12;

    /**
     * 默认字母颜色
     */
    private static final int DEFAULT_INITIAL_LETTER_COLOR = Color.parseColor("#298BFF");
    /**
     * 默认选择字母时的颜色
     */
    private static final int DEFAULT_SELECTED_LETTER_COLOR = DEFAULT_INITIAL_LETTER_COLOR;

    /**
     * 默认在屏幕中央的字母颜色
     */
    private static final int DEFAULT_SCREEN_LETTER_COLOR = Color.parseColor("#ff0099cc");

    /**
     * 字母表按压时的颜色
     */
    private static final int DEFAULT_PRESSING_ALPHABET_COLOR = Color.parseColor("#44000000");

    /**
     * 默认选择字母的背景颜色
     */
    private static final int DEFAULT_SELECT_LETTER_BG_COLOR = Color.parseColor("#12000000");

    /**
     * 默认初始化字母的背景颜色
     */
    private static final int DEFAULT_INITIAL_LETTER_BG_COLOR = Color.parseColor("#00000000");

    /**
     * 圆角半径
     */
    private static final int POPUP_RADIUS_DP = 8;

    //widgets
    private PopupWindow mPopupWindow;
    private TextView mLetterInPopupTv;

    //arguments
    /**
     * 字母颜色
     */
    private int mInitialLetterColor = DEFAULT_INITIAL_LETTER_COLOR;

    /**
     * 字母背景色
     */
    private int mInitialLetterBgColor = DEFAULT_INITIAL_LETTER_BG_COLOR;

    /**
     * 字母被选择时的颜色
     */
    private int mSelectedLetterColor = DEFAULT_SELECTED_LETTER_COLOR;

    /**
     * 字母被选择时背景的颜色
     */
    private int mSelectedLetterBgColor = DEFAULT_SELECT_LETTER_BG_COLOR;
    /**
     * 字母在屏幕中央的颜色
     */
    private int mScreenLetterColor = DEFAULT_SCREEN_LETTER_COLOR;

    private int mPopupBackgroundColor = Color.parseColor("#55000000");
    /**
     * 字母表按压时的颜色
     */
    private int mAlphabetColorWhenActionDown = DEFAULT_PRESSING_ALPHABET_COLOR;
    /**
     * 松开字母表时的颜色
     */
    private int mAlphabetColorWhenActionUp = Color.parseColor("#00000000");
    /**
     * 在字母表里的字母大小
     */
    private float mAlphabetLetterSize = DEFAULT_ALPHABET_LETTER_SIZE;
    /**
     * 屏幕中央的字母大小
     */
    private float mScreenLetterSize = DEFAULT_SCREEN_LETTER_SIZE;


    /**
     * RxBus事件
     */
    private SelectLetterEvent mSelectLetterEvent;
    /**
     * 字母集合
     */
    private List<String> mLetterList;
    /**
     * 字母控件集合
     */
    private List<TextView> mTxtViewList;
    /**
     * 上一个触摸的Y轴值
     */
    private float mLastY;
    /**
     * 触摸滑动过程中,总的垂直偏移量
     */
    private float mTotalOffsetInVerticalMove;
    /**
     * 一个字母控件的高度
     */
    private float mLetterVerticalHeight;
    /**
     * 当前触摸到的字母
     */
    private String mCurrentTouchLetter;
    /**
     * 当前触摸到的字母的序号
     */
    private int mCurrentTouchLetterIndex;
    /**
     * 上一次列表字母滑动的位置
     */
    private int mLastReactionBgPosition;


    public AlphabetLinearLayout(Context context) {
        super(context);
        init(context);
    }

    public AlphabetLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AlphabetLinearLayout);
        mInitialLetterColor = typedArray.getColor(R.styleable.AlphabetLinearLayout_letterColor, DEFAULT_INITIAL_LETTER_COLOR);
        mSelectedLetterColor = typedArray.getColor(R.styleable.AlphabetLinearLayout_selectedLetterColor, DEFAULT_SELECTED_LETTER_COLOR);
        mSelectedLetterBgColor = typedArray.getColor(R.styleable.AlphabetLinearLayout_selectedLetterBgColor, DEFAULT_SELECT_LETTER_BG_COLOR);
        mScreenLetterColor = typedArray.getColor(R.styleable.AlphabetLinearLayout_screenLetterColor, DEFAULT_SCREEN_LETTER_COLOR);
        mAlphabetColorWhenActionDown = typedArray.getColor(R.styleable.AlphabetLinearLayout_pressAlphabetColor, DEFAULT_PRESSING_ALPHABET_COLOR);

        mScreenLetterSize = typedArray.getDimension(R.styleable.AlphabetLinearLayout_screenLetterSize, DEFAULT_SCREEN_LETTER_SIZE);
        mAlphabetLetterSize = typedArray.getDimension(R.styleable.AlphabetLinearLayout_letterSize, DEFAULT_ALPHABET_LETTER_SIZE);
        typedArray.recycle();

        init(context);
    }

    private void init(Context context) {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        mSelectLetterEvent = new SelectLetterEvent();

        mLetterList = Arrays.asList(mLetters);
        mTxtViewList = new LinkedList<>();

        int length = mLetters.length;
        TextView letterTv;
        for (int i = 0; i < length; i++) {
            letterTv = new TextView(context);
            letterTv.setPadding(DEFAULT_LETTER_PADDING_LEFT, 0, DEFAULT_LETTER_PADDING_RIGHT, 0);
            letterTv.setText(mLetters[i]);
            letterTv.setTextColor(mInitialLetterColor);
            letterTv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAlphabetLetterSize);
            letterTv.setGravity(Gravity.CENTER);
            letterTv.setOnTouchListener(this);

            mTxtViewList.add(letterTv);
            this.addView(letterTv);
        }

        //设置PopupWindow
        mLetterInPopupTv = new TextView(context);
        mLetterInPopupTv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mScreenLetterSize);
        mLetterInPopupTv.setTextColor(mScreenLetterColor);
        mLetterInPopupTv.setGravity(Gravity.CENTER);

        mPopupWindow = new PopupWindow(screenWidth / 4, screenWidth / 4);

        ShapeDrawable shapeDrawable = new ShapeDrawable();
        int radius = getDpToPx(getContext(), POPUP_RADIUS_DP);
        shapeDrawable.setShape(new RoundRectShape(new float[]{radius, radius, radius, radius, radius, radius, radius, radius}, null, null));
        shapeDrawable.getPaint().setColor(mPopupBackgroundColor);
        shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
        mPopupWindow.setBackgroundDrawable(shapeDrawable);
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setContentView(mLetterInPopupTv);

        mLetterVerticalHeight = getDpToPx(context, mAlphabetLetterSize * SCREEN_COMPAT_FACTOR);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 屏蔽自己的触摸事件
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }

    @Override
    public boolean onTouch(View v, final MotionEvent event) {
        if (v instanceof TextView) {
            TextView txtLetter = (TextView) v;
            if (event != null) {
                int eventAction = event.getAction();
                switch (eventAction) {
                    case MotionEvent.ACTION_DOWN:

                        this.setBackgroundColor(mAlphabetColorWhenActionDown);
                        if (mLastReactionBgPosition > 0 && mLastReactionBgPosition < mTxtViewList.size()) {
                            mTxtViewList.get(mLastReactionBgPosition).setBackgroundColor(mInitialLetterBgColor);
                        }

                        mCurrentTouchLetter = txtLetter.getText().toString().trim();
                        mLetterInPopupTv.setText(mCurrentTouchLetter);
                        mCurrentTouchLetterIndex = mLetterList.indexOf(mCurrentTouchLetter);

                        //发送显示字母
                        mSelectLetterEvent.setCurrentLetter(mCurrentTouchLetter);
                        RxBus.getInstance().send(mSelectLetterEvent);
                        //在屏幕里显示字母
                        if (!mPopupWindow.isShowing()) {
                            mPopupWindow.showAtLocation(v.getRootView(), Gravity.CENTER, 0, 0);
                        }

                        break;
                    case MotionEvent.ACTION_MOVE:
                        //使用屏幕原生坐标计算距离
                        float currentY = event.getRawY();
                        if (mLastY > 0) {
                            float value = currentY - mLastY;
                            mTotalOffsetInVerticalMove += value;
                            int spanNumber = (int) (mTotalOffsetInVerticalMove / mLetterVerticalHeight);

                            //待显示的字母在集合中的序号
                            int order = mCurrentTouchLetterIndex + spanNumber;
                            if (order < 0) {
                                order = 0;
                            }
                            if (order >= mLetterList.size()) {
                                order = mLetterList.size() - 1;
                            }

                            //显示当前触摸的字母
                            mCurrentTouchLetter = mLetterList.get(order);
                            mLetterInPopupTv.setText(mCurrentTouchLetter);
                            //发送当前触摸的字母的序号
                            mSelectLetterEvent.setCurrentLetter(mCurrentTouchLetter);
                            RxBus.getInstance().send(mSelectLetterEvent);
                        }

                        mLastY = currentY;
                        break;

                    case MotionEvent.ACTION_UP:
                        if (mPopupWindow.isShowing()) {
                            mPopupWindow.dismiss();
                        }
                        mTotalOffsetInVerticalMove = 0;
                        mLastY = 0;
                        this.setBackgroundColor(mAlphabetColorWhenActionUp);
                        reactiveSelectLetterBg(mCurrentTouchLetter);
                        break;
                    case MotionEvent.ACTION_CANCEL:

                        break;
                }
            }
        }
        return true;
    }

    private int getDpToPx(Context context, float dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5);
    }

    public void reactiveSelectLetterBg(String letter) {
        reactiveSelectLetterBg(letter, 0);
    }

    public void reactiveSelectLetterBg(String letter, @ColorRes int bgColorRes) {
        if (!TextUtils.isEmpty(letter)) {
            if (mLetterList.contains(letter)) {
                int currentPosition = mLetterList.indexOf(letter);
                if (currentPosition <= mTxtViewList.size()) {
                    if (mLastReactionBgPosition != currentPosition) {
                        mTxtViewList.get(mLastReactionBgPosition).setBackgroundColor(mInitialLetterBgColor);
                    }

                    if (bgColorRes != 0) {
                        mTxtViewList.get(currentPosition).setBackgroundColor(getResources().getColor(bgColorRes));
                    } else {
                        mTxtViewList.get(currentPosition).setBackgroundColor(mSelectedLetterBgColor);
                    }
                }
                if (mLastReactionBgPosition != currentPosition) {
                    mLastReactionBgPosition = currentPosition;
                }
            }
        }
    }


//    public void setLetterColor(String letter) {
//        setLetterColor(letter, 0);
//    }
//
//    public void setLetterColor(String letter, @ColorRes int colorRes) {
//        if (!TextUtils.isEmpty(letter)) {
//            if (mLetterList.contains(letter)) {
//                int currentPosition = mLetterList.indexOf(letter);
//                if (currentPosition <= mTxtViewList.size()) {
//                    if (mLastReactionPosition != currentPosition) {
//                        mTxtViewList.get(mLastReactionPosition).setTextColor(mInitialLetterColor);
//                    }
//                    if (colorRes != 0) {
//                        mTxtViewList.get(currentPosition).setTextColor(getResources().getColor(colorRes));
//                    } else {
//                        mTxtViewList.get(currentPosition).setTextColor(mSelectedLetterColor);
//                    }
//                }
//                if (mLastReactionPosition != currentPosition) {
//                    mLastReactionPosition = currentPosition;
//                }
//            }
//        }
//    }

//    public void setInitialLetterInAlphabet() {
//        for (TextView letter : mTxtViewList) {
//            letter.setTextColor(mInitialLetterColor);
//        }
//    }

}
